#-*-coding:utf-8-*-
#author:Hsianglee
import os
import urllib
import re
from lxml import etree
import requests
import sys
from bs4 import BeautifulSoup

class ZhengfangSpider:

    def __init__(self,studentID,password,baseUrl):
        print "本脚本适用于正方教务系统"
        reload(sys)
        sys.setdefaultencoding("utf-8")
        self.studentID = studentID
        self.password = password
        self.baseUrl = baseUrl
        self.session = requests.session()

    def login(self):
        loginUrl = self.baseUrl+"/default2.aspx"
        response = self.session.get(loginUrl)
        selector = etree.HTML(response.content)
        print self.session.cookies
        __VIEWSTATE = selector.xpath('//*[@id="form1"]/input/@value')[0]
        imgUrl = self.baseUrl+"/CheckCode.aspx?"
        imgresponse = self.session.get(imgUrl, stream=True)
        image = imgresponse.content
        DstDir = os.getcwd() + "\\"
        print("保存验证码到：" + DstDir + "code.jpg" + "\n")
        try:
            with open(DstDir + "code.jpg", "wb") as jpg:
                jpg.write(image)
        except IOError:
            print("IO Error\n")
        finally:
            jpg.close
        code = raw_input("请您输入验证码:")
        data = {
            "__VIEWSTATE": __VIEWSTATE,
            "txtUserName": self.studentID,
            "TextBox2": self.password,
            "txtSecretCode": code,
            "Button1": "",
        }
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
        }
        headers = self.session.headers
        response = self.session.post(loginUrl, data=data, headers=headers)
        return response
        print "成功进入教务系统!"


    def getInfor(self,response,xpath):
        content = response.content.decode('gb2312') #网页源码是gb2312要先解码
        selector = etree.HTML(content)
        text = selector.xpath(xpath)[0]
        text = text.replace(" ", "")
        text = text[0:2]
        UrlName = urllib.quote_plus(str(text.encode('gb2312')))
        print text + "同学，您已登陆成功，欢迎您!"
        return UrlName


    def getClassSchedule(self,urlName):
        classUrl = self.baseUrl+"/xskbcx.aspx?xh="+self.studentID+"&xm="+urlName+"&gnmkdm=N121603"
        headers = {
            "Referer": self.baseUrl+"/xs_main.aspx?xh="+self.studentID,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
        }
        response = self.session.get(classUrl, headers=headers)
        html = response.content.decode("gb2312")
        #soup = BeautifulSoup(html, "html.parser")
        #print soup
        # 获取解析后的内容
        selector=etree.HTML(html)
        content = selector.xpath('//*[@id="Table1"]/tr/td/text()')
        for each in content:
            print each

if __name__ == '__main__':
    studentID = raw_input("请输入您的学号:")
    password = raw_input("请输入您的密码:")
    #输入您所在学校的教务系统首页地址
    baseUrl = ""
    spider = ZhengfangSpider(studentID,password,baseUrl)

    try:
        response = spider.login()
        xpath = '//*[@id="xhxm"]/text()'
        stu_UrlName = spider.getInfor(response, xpath)
        spider.getClassSchedule(stu_UrlName)

    except Exception,e:
        print Exception,":",e